package com.bankcomm.ui.specialwidget;

import java.util.ArrayList;
import java.util.List;
import org.json.JSONArray;
import org.json.JSONObject;
import android.app.Activity;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Bitmap;
import android.graphics.Camera;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.drawable.Drawable;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Transformation;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Gallery;
import android.widget.ImageSwitcher;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ViewSwitcher.ViewFactory;
import com.bankcomm.R;
import com.bankcomm.bean.*;
import com.bankcomm.common.LPMid;
import com.bankcomm.ui.BaseViewCopy;
import com.rytong.tools.ui.Component;
import com.rytong.tools.utils.AsyncImageLoader;
import com.rytong.tools.utils.AsyncImageLoader.ImageCallBack;
import com.rytong.tools.utils.Utils;

public class LPCoverFlow extends Component {
	@Override
	public void initRealView(Activity activity, String nodeValue) {
		realView_ = new MyCoverFlow(activity);
	}
	
	class MyCoverFlow extends RelativeLayout implements CompositedComponent {
		private ArrayList<CoverInfo> items = null;
		private CoverFlow coverflow = null;
		private LinearLayout flowWrap = null;
		private TextView flowTitle = null;
		private TextView flowDirector = null;
		private TextView flowPersonator = null;
		private TextView flowType = null;
		private String _oKind = null;
		private String[] imgs = null;
		
		public MyCoverFlow(Context context) {
			super(context);
			items = new ArrayList<CoverInfo>();
			
			// 获得特殊属性值 cards
			Object _oCards = getPropertyByName("covers"); 
			_oKind = getPropertyByName("kind");
			if (_oKind.equals("imgUrl") && _oKind.length() >0) {
				String imgSrc = getPropertyByName("imgsrc");
				imgs = imgSrc.split(",");
			} else {
				if (_oCards != "") {
					try {
						JSONArray cardsJA = new JSONArray(_oCards.toString());
						for (int i = 0; i < cardsJA.length(); i++) {
							CoverInfo coverInfo = new CoverInfo();
							JSONObject cardsJO = (JSONObject) cardsJA.get(i);
							if (cardsJO.has(CoverInfo.KEY_COVER)) {
								coverInfo.setCover(cardsJO.getString(CoverInfo.KEY_COVER));
							}
							if (cardsJO.has(CoverInfo.KEY_TITLE)) {
								coverInfo.setTitle(cardsJO.getString(CoverInfo.KEY_TITLE));
							}
							if (cardsJO.has(CoverInfo.KEY_DIRECTOR)) {
								coverInfo.setDirector(cardsJO.getString(CoverInfo.KEY_DIRECTOR));
							}
							if (cardsJO.has(CoverInfo.KEY_PERSONATOR)) {
								coverInfo.setPersonator(cardsJO.getString(CoverInfo.KEY_PERSONATOR));
							}
							if (cardsJO.has(CoverInfo.KEY_TYPE)) {
								coverInfo.setType(cardsJO.getString(CoverInfo.KEY_TYPE));
							}
							if (cardsJO.has(CoverInfo.KEY_HYPERLINK)) {
								coverInfo.setHyperLink(cardsJO.getString(CoverInfo.KEY_HYPERLINK));
							}

							items.add(coverInfo);
						}
					} catch (Exception je) {
						je.printStackTrace();
					}
				}
			}
			setLayoutParams(new RelativeLayout.LayoutParams(
					LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));
			setGravity(Gravity.CENTER_HORIZONTAL);
			
			coverflow = new CoverFlow(context);
			
			/** 设置适配器 */
			coverflow.imgAdapter = coverflow.createOwnAdapter(context, items, imgs);
			coverflow.setAdapter(coverflow.imgAdapter);
			
			int size = 0;
			if (items != null && items.size() > 0) {
				size = items.size();
			} else if (imgs != null && imgs.length > 0) {
				size = imgs.length;
			}
			if(size > 0) {
				coverflow.setSelection(size / 2);
			}
			
			RelativeLayout.LayoutParams rlp1 = new RelativeLayout.LayoutParams(
					LayoutParams.FILL_PARENT, Utils.getScaledValueY(180));
			rlp1.addRule(RelativeLayout.CENTER_HORIZONTAL);
			rlp1.addRule(RelativeLayout.ALIGN_PARENT_TOP);
			
			addView(coverflow, rlp1);
			
			if (!_oKind.equals("imgUrl")) {
				flowWrap = (LinearLayout) LayoutInflater.from(context).inflate(R.layout.coverflow_item_layout, null);
				flowWrap.setOrientation(LinearLayout.VERTICAL);
//				flowWrap.setGravity(Gravity.CENTER);
				flowTitle = (TextView) flowWrap.findViewById(R.id.flow_title);
				flowDirector = (TextView) flowWrap.findViewById(R.id.director);
				flowPersonator = (TextView) flowWrap.findViewById(R.id.personator);
				flowType = (TextView) flowWrap.findViewById(R.id.type);

				RelativeLayout.LayoutParams rlp2 = new RelativeLayout.LayoutParams(
						LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT);
//				rlp2.addRule(RelativeLayout.CENTER_HORIZONTAL);
				rlp2.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
				addView(flowWrap, rlp2);
			}
			
			setBackgroundColor(Color.TRANSPARENT);
		}
		
		@Override
		public Component composited() {
			return LPCoverFlow.this;
		}
		
		class CoverFlow extends Gallery implements OnItemSelectedListener, ViewFactory, OnItemClickListener {
			private Camera mCamera = new Camera();
			private int mMaxRotationAngle = 50;		// 最大旋转角度
			private int mMaxZoom = -500;			// 最大缩放值
			private int mCoveflowCenter;			// 半径值
			private boolean mAlphaMode = true;
			private boolean mCircleMode = false;
			private BaseViewCopy bv_;
			
			public int selectedIndex_ = -1;
			ImageAdapter imgAdapter = null;
			
			//电影票等待图片
			private Drawable waiting = null;
			//图片下载类
			AsyncImageLoader imageLoader = null;
			
			public CoverFlow(Context context) {
				super(context);
				bv_ = (BaseViewCopy) context;
				this.setOnItemSelectedListener(this);
				this.setOnItemClickListener(this);
				setAnimationDuration(1200);
				// 支持转换，执行 getChildStaticTransformation 方法
				this.setStaticTransformationsEnabled(true);
				
				if(null == waiting){
					waiting = LPMid.getLoadingImage(context);					
				}
				
				if(null == imageLoader){
					imageLoader = Utils.getAsyncImageLoader();
				}
			}
			
			@Override
			public boolean onTouchEvent(android.view.MotionEvent event) {
				switch (event.getAction()) {
				case MotionEvent.ACTION_DOWN:
					if(hs_ != null){
						hs_.focusObj_ = this;
					}
					break;
				case MotionEvent.ACTION_UP:
					if(hs_ != null){
						hs_.focusObj_ = null;
					}
					break;
				default:
					break;
				}
				return super.onTouchEvent(event);
			};
			
			public int getMaxRotationAngle() {
				return mMaxRotationAngle;
			}

			public void setMaxRotationAngle(int maxRotationAngle) {
				mMaxRotationAngle = maxRotationAngle;
			}

			public boolean getCircleMode() {
				return mCircleMode;
			}

			public void setCircleMode(boolean isCircle) {
				mCircleMode = isCircle;
			}

			public boolean getAlphaMode() {
				return mAlphaMode;
			}

			public void setAlphaMode(boolean isAlpha) {
				mAlphaMode = isAlpha;
			}

			public int getMaxZoom() {
				return mMaxZoom;
			}

			public void setMaxZoom(int maxZoom) {
				mMaxZoom = maxZoom;
			}
			
			private int getCenterOfCoverflow() {
				return (getWidth() - getPaddingLeft() - getPaddingRight()) / 2 + getPaddingLeft();
			}

			private int getCenterOfView(View view) {
				return view.getLeft() + view.getWidth() / 2;
			}
			
			// 控制gallery中每个图片的旋转(重写gallery中的方法)
			@Override
			protected boolean getChildStaticTransformation(View child,
					Transformation t) {
				// 取得当前子View的半径值
				final int childCenter = getCenterOfView(child);
				final int childWidth = child.getWidth();

				// 旋转角度
				int rotationAngle = 0;
				// 重置转换状态
				t.clear();
				// 设置转换类型
				t.setTransformationType(Transformation.TYPE_MATRIX);
				// 如果图片位于中心位置不需要进行旋转
				if (childCenter == mCoveflowCenter) {
					transformImageBitmap((ImageView) child, t, 0, 0);
				} else {
					rotationAngle = (int) (((float) (mCoveflowCenter - childCenter) / childWidth) * mMaxRotationAngle);
					if (Math.abs(rotationAngle) > mMaxRotationAngle) {
						rotationAngle = (rotationAngle < 0) ? -mMaxRotationAngle : mMaxRotationAngle;
					}
					transformImageBitmap((ImageView) child, t, rotationAngle, (int) Math.floor((mCoveflowCenter - childCenter)
							/ (childWidth == 0 ? 1 : childWidth)));
				}
				return true;
			}
			
			protected void onSizeChanged(int w, int h, int oldw, int oldh) {
				mCoveflowCenter = getCenterOfCoverflow();
				super.onSizeChanged(w, h, oldw, oldh);
			}

			/**
			 * Transform the Image Bitmap by the Angle passed
			 * 
			 * @param imageView
			 *            ImageView the ImageView whose bitmap we want to rotate
			 * @param t
			 *            transformation
			 * @param rotationAngle
			 *            the Angle by which to rotate the Bitmap
			 */
			private void transformImageBitmap(ImageView child, Transformation t, int rotationAngle, int d) {
				// 对效果进行保存
				mCamera.save();
				final Matrix imageMatrix = t.getMatrix();
				// 图片高度
				final int imageHeight = child.getLayoutParams().height;
				// 图片宽度
				final int imageWidth = child.getLayoutParams().width;
				// 返回旋转角度绝对值
				final int rotation = Math.abs(rotationAngle);
				// 在Z轴上正向移动camera的视角，实际效果为放大图片。
				// 如果在Y轴上移动，则图片上下移动；X轴上对应图片左右移动。
				mCamera.translate(0.0f, 0.0f, 100.0f);
				// As the angle of the view gets less, zoom in
				if (rotation <= mMaxRotationAngle) {
					float zoomAmount = (float) (mMaxZoom + (rotation * 1.5));
					mCamera.translate(0.0f, 0.0f, zoomAmount);
					if (mCircleMode) {
						if (rotation < 20)
							mCamera.translate(0.0f, 0.0f, 355);
						else
							mCamera.translate(0.0f, 0.0f, (555 - rotation * 2.5f));
					}
				}
				// 在Y轴上旋转，对应图片竖向向里翻转。
				// 如果在X轴上旋转，则对应图片横向向里翻转。
				mCamera.rotateY(rotationAngle);
				mCamera.getMatrix(imageMatrix);

				imageMatrix.preTranslate(-(imageWidth / 2), -(imageHeight / 2));
				imageMatrix.postTranslate((imageWidth / 2), (imageHeight / 2));
				mCamera.restore();
			}

			@Override
			public void onItemSelected(AdapterView<?> parent, View view,
					int arg2, long arg3) {
				selectedIndex_ = arg2;
				if(imgAdapter != null && imgAdapter.getCount() > 0) {
					Object obj_ = imgAdapter.getItem(arg2);
					CoverInfo ci = null;
					String imgUrl = null;
					if (obj_ instanceof String) {
						imgUrl = (String) obj_;
					}
					if (obj_ instanceof CoverInfo) {
						ci = (CoverInfo) obj_;
						flowTitle.setText(ci.getTitle());
						flowDirector.setText(ci.getDirector());
						flowPersonator.setText(ci.getPersonator());
						flowType.setText(ci.getType());
					}
					
					/** 加载中间五张图片, 第  n 项表达式是An = arg2 + (-1)^(n+1) * (n / 2) 
					 * 
					 * 1. 加载中央那张先
					 * 2. 加载前两张
					 * 3. 加载后两张	
					 * 计算次数的变量
					 * */
					int n = 1;
					int des = 0;
					while(n <= 5) {
						des = arg2 + (n / 2) * ((n % 2 == 0) ? -1 : 1);
						if(des >= 0 && des < imgAdapter.getCount()) {
							if (ci != null) {
								ci = (CoverInfo) imgAdapter.getItem(des);
								imageLoader.downloadBitmap(getContext(),ci.getCover(), callBack);
							} else if (imgUrl != null && imgUrl.length() > 0) {
								imageLoader.downloadBitmap(getContext(),imgUrl, callBack);
							}
						}
						n++;
					}
					postInvalidate();
				}
			}

			/**
			 * 图片下载的回调接口
			 */
			private ImageCallBack callBack = new ImageCallBack() {
				
				@Override
				public void loadImageSuccess(Bitmap bitmap, String url) {
					// TODO Auto-generated method stub
					imgAdapter.notifyDataSetChanged();
				}
			};
			
			@Override
			public void onNothingSelected(AdapterView<?> parent) {
				
			}

			@Override
			public View makeView() {
				ImageView imageView = new ImageView(bv_);
				imageView.setBackgroundColor(0xFF000000);
				imageView.setScaleType(ImageView.ScaleType.FIT_CENTER);
				imageView.setLayoutParams(new ImageSwitcher.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));
				return imageView;
			}

			@SuppressWarnings("rawtypes")
			@Override
			public void onItemClick(AdapterView<?> parent, View arg1,
					int position, long arg3) {
				if (position == selectedIndex_) {
					Object obj = imgAdapter.getItem(position);
					if( obj instanceof String){
						//String url = String.valueOf(obj);
						//if(null != url && !"".equalsIgnoreCase(url)){
						//	LPMid.getInstance().um_.dealWithLink(url, bv_);
						//}
					}else if(obj instanceof CoverInfo){
						CoverInfo clickItem_ = (CoverInfo)obj;
						String sUrl = clickItem_.getHyperLink();
						if ((null != clickItem_) && (null != sUrl)) {
							try {
								// 提交表单数据, 比如城市
								StringBuilder buf = new StringBuilder();
								ArrayList list = Component.VWIDGETARRAY;
								if(null != list && list.size() > 0){
									for (int i = 0; i < list.size(); i++) {
										Object comp = list.get(i);
										if (comp instanceof LPCityChooser) {
											LPCityChooser cityChooser = (LPCityChooser) comp;
											buf.append("&");
											buf.append(cityChooser.getPropertyByName("name"));
											buf.append("=");
											buf.append(Utils.escapeURIComponent(cityChooser.getCityValue()));
											buf.append("&");
											break;
										}
									}
									// 刷新页面
									if(buf.length() > 0) {
										buf.deleteCharAt(buf.length() - 1);
										//bv_.getRightReply(bv_, bv_.right, sUrl, buf.toString());
										sUrl = sUrl.concat(buf.toString());
										LPMid.getInstance().um_.dealWithLink(sUrl, bv_);
									} else {
										//bv_.getRightReply(bv_, bv_.right, sUrl, null);
										LPMid.getInstance().um_.dealWithLink(sUrl, bv_);
									}
								}
							} catch (Exception e) {
								Utils.printException(e);
							}
						}
					}
				}
			}
			
			void coverPressed(CoverInfo clickItem) throws Exception {
			}
			
			private ImageAdapter createOwnAdapter(Context context, List<CoverInfo> items, String[] imgs) {
				if (_oKind.equals("imgUrl") && _oKind.length() > 0) {
					return new ImageAdapter(context, imgs);
				} else {
					return new ImageAdapter(context, items);
				}
			}
			
			
			class ImageAdapter extends BaseAdapter {
				int mGalleryItemBackground;
				private Context mContext;
				private List<CoverInfo> lvalue;
				private String[] imgs;

				public ImageAdapter(Context c, List<CoverInfo> items) {
					this.mContext = c;
					lvalue = items;
					
					if (null == lvalue) {
						lvalue = new ArrayList<CoverInfo>();
					}
					
					TypedArray typedArray = c.obtainStyledAttributes(R.styleable.Gallery1);
					mGalleryItemBackground = typedArray.getResourceId(R.styleable.Gallery1_android_galleryItemBackground, 0);
				}
				
				public ImageAdapter(Context c, String[] imgs) {
					this.mContext = c;
					this.imgs = imgs;
					if (imgs == null) {
						this.imgs = new String[]{};
					}
				}
				
				public void setDate(List<CoverInfo> items) {
					lvalue = items;
					this.notifyDataSetChanged();
				}
				
				@Override
				public int getCount() {
					if (lvalue != null && lvalue.size() > 0) {
						return lvalue.size();
					}
					if (imgs != null && imgs.length > 0) {
						return imgs.length;
					}
					return 0;
				}

				@Override
				public Object getItem(int position) {
					if (lvalue != null && lvalue.size() > 0) {
						return lvalue.get(position);
					}
					if (imgs != null && imgs.length > 0) {
						return imgs[position];
					}
					return position;
				}

				@Override
				public long getItemId(int position) {
					return position;
				}

				@Override
				public View getView(int position, View convertView,
						ViewGroup parent) {
					View retView = convertView;
					if (convertView == null) {
						retView = composeItem(position);
					}
					if (mAlphaMode && retView != null) {
						int alpha = (255 - 5 * Math.abs(position - selectedIndex_));
						if (alpha < 10) {
							alpha = 10;
						}
						((ImageView)(retView)).setAlpha(alpha);
					}
					return retView;
				}

				private View composeItem(int position) {
					ImageView iv = new ImageView(mContext);
					//iv.setScaleType(ScaleType.FIT_XY);
					
					Bitmap bitmap = null;
					if (lvalue != null && lvalue.size() > 0) {
						CoverInfo ci = lvalue.get(position);
						bitmap = imageLoader.getBitmapFromCache(ci.getCover());
						if(null != bitmap){
							bitmap = Utils.createReflectedImage(bitmap);
							iv.setImageBitmap(bitmap);
						}else{
							iv.setImageDrawable(waiting);
						}
						iv.setTag(ci.getCover());
					}
					
					if (imgs != null && imgs.length > 0) {
						String img = imgs[position];
						bitmap = imageLoader.getBitmapFromCache(img);
						if(null != bitmap){
							bitmap = Utils.createReflectedImage(bitmap);
							iv.setImageBitmap(bitmap);
						}else{
							iv.setImageDrawable(waiting);
						}
						iv.setTag(img);
					}
					
					iv.setLayoutParams(new Gallery.LayoutParams(Utils.getScaledValueX(100),Utils.getScaledValueY(55)));
					return iv;
				}
			}
		}
	}
}
